<?php
header ("Content-type: text/xml");
include 'Library/CouchDb/Couch.php';
include 'Library/Shrink.php';
$couch = new Couch('localhost', 'bugshrink');

if(!$couch->running() || !$couch->db_exists()) {
	die();
}
$lastUpdate = '';

$bugs = $couch->get_all('allfull', $options = array('reverse' => 'true'));
if(($bugs !== false) && (count($bugs) > 0)) {
	
	$lastUpdate = '';
	foreach($bugs AS $id => $bug) {
		if(strlen($bug->get('Subject')) == 0) {continue;}
		
		//get newest bug
		if($bug->get('CreationDate') > $lastUpdate) {
			$lastUpdate = $bug->get('CreationDate');
		}
	}
}

function get_iso_8601_date($int_date) {
   //$int_date: current date in UNIX timestamp
   $date_mod = date('Y-m-d\TH:i:s', $int_date);
   $pre_timezone = date('O', $int_date);
   $time_zone = substr($pre_timezone, 0, 3).":".substr($pre_timezone, 3, 2);
   $date_mod .= $time_zone;
   return $date_mod;
}
//var_dump( strtotime(str_replace(':', '', $lastUpdate)));
$lastUpdate = get_iso_8601_date(strtotime(str_replace(':', '', $lastUpdate)));

echo '<?xml version="1.0" encoding="utf-8"?>';
?><feed xmlns="http://www.w3.org/2005/Atom">

  <title>BugShrink Feed</title> 
  <link href="http://demos.couchdb.com/BugShrink2/"/>
  <updated><?=$lastUpdate?></updated>
  <author> 
    <name>BugShrink Bug Tracking Demo for CouchDb</name>
  </author> 
  <id>urn:uuid:<?=md5('http://demos.couchdb.com/BugShrink2/')?></id>

<?php
foreach($bugs AS $id => $bug) {
	if(strlen($bug->get('Subject')) == 0) {continue;}
	$Subject = $bug->get('Subject');
	$Link = 'http://demos.couchdb.com/BugShrink2/?id='.$id;
	$updated = get_iso_8601_date(strtotime(str_replace(':', '', $bug->get('CreationDate'))));
	$Body = shrink_format_body($bug->get('Body'));
	$By = $bug->get('Author');
	echo <<<EOD
  <entry>
    <title>$Subject</title>
	<author>$By</author>
    <link href="$Link"/>
    <id>urn:uuid:$id</id>
    <updated>$updated</updated>
    <published>$updated</published>
    <content type="xhtml">$Body</content>
  </entry>
	
EOD;
}

?>
</feed>